#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2020/6/21 15:50
# @file     : table_crud.py
# @Software : PyCharm
# ======================================#

from apps.client.redis_client import Redis
from apps.decorate.redis_table import redis_table_all_cache, redis_delete_cache
from apps.models.dboperator import query_table_data, insert_table_data, update_table_data, delete_table_data, query
from apps.settings import REDIS_CACHE_TABLES, REDIS_FLUSHDB_SECRET


def tables_redis_flush_tables():
    """清除redis tables info"""
    infos = {
        "status": True,
        "msg": "ok"
    }
    for table in REDIS_CACHE_TABLES:
        Redis.delete(f"table_{table}")
    return infos


def tables_redis_flushdb(evileye=None):
    """清除redis tables info"""
    infos = {
        "status": True,
        "msg": "ok"
    }
    if evileye != REDIS_FLUSHDB_SECRET:
        infos["status"] = False
        infos["msg"] = "secret is required, when redis flushdb"

    for key in Redis.keys():
        Redis.delete(key)
    return infos


def query_info(sql, data=None, fetchone=False):
    """
    :param sql:  sql语句
    :param data: sql语句变量，防sql注入
    :param fetchone: True:取一条 False: 数组
    :return: 查询结果为空，status修改为False
    """
    records = query(sql, data, fetchone)
    if records["status"] and not records["data"]:
        records["status"] = False
        records["msg"] = "not found any record!"
    return records


@redis_table_all_cache
def query_table_info(table, where=None, fetchone=False, is_and=True):
    records = query_table_data(table, where, is_and, fetchone)
    if records["status"] and not records["data"]:
        records["status"] = False
        records["msg"] = f"{table}: not found any record, where:{where}, is_and:{is_and}"
    return records


@redis_table_all_cache
def query_table(table, where=None, fetchone=False, is_and=True):
    """
    :param table: 查询的表明
    :param where: 查询的条件，get参数
    :param is_and: 默认多个条件是and
    :return: list
    """
    records = query_table_data(table, where, fetchone, is_and)
    return records


@redis_delete_cache
def insert_table(table, data):
    """
    非事务类型，执行完成功即提交
    :param table:  insert表名
    :param data:   insert表数据
    :return:        True/False
    """
    infos = insert_table_data(table, data)
    return infos


@redis_delete_cache
def update_table(table, data):
    """
    非事务类型，执行完成功即提交
    :param table:  update表名
    :param data:   update表数据
    :param id:     where条件
    :return:       True/False
    """
    infos = update_table_data(table, data)
    return infos


@redis_delete_cache
def delete_table(table, id):
    """
    非事务类型，执行完成功即提交
    :param table:   delete表名
    :param id:      delete表数据id
    :return:        True/False
    """
    infos = delete_table_data(table, id)
    return infos


def transaction_op(cursor, sqls):
    """
    :param cursor:
    :param sqls:[(sql1,value),(sql2,value),(sql3,value)]
    :return:
    """
    infos = {
        "status": True,
        "msg": "ok"
    }
    try:
        for sql, params in sqls:
            cursor.execute(sql, params)
    except Exception as e:
        infos["status"] = False
        infos["msg"] = f"Error: {e}"
    return infos
